package com.cxyd.modules.job.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class TcpClient {
    public static String sendAndReceive(String ip, int port, String message) throws IOException {
        try (Socket socket = new Socket(ip, port)) {
            // 设置超时时间（可选）
            socket.setSoTimeout(5000);

            // 发送数据
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(message.getBytes());
            outputStream.flush();

            // 接收响应
            InputStream inputStream = socket.getInputStream();
            byte[] buffer = new byte[1024];
            int length = inputStream.read(buffer);
            if (length > 0) {
                return new String(buffer, 0, length);
            }
            return null;
        }
    }
}
